package com.tongjie.hotelbooking.im.conversation.service;

import com.tongjie.hotelbooking.im.conversation.entiry.Conversation;
import com.tongjie.hotelbooking.im.conversation.entiry.MemberConversation;
import com.tongjie.hotelbooking.im.conversation.repository.ConversationRepository;
import com.tongjie.hotelbooking.im.conversation.repository.MemberConversationRepository;
import com.tongjie.hotelbooking.security.SecurityHelper;
import com.tongjie.hotelbooking.user.entity.User;
import com.tongjie.hotelbooking.user.repository.UserRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.lang.reflect.Member;
import java.util.Date;
import java.util.UUID;

@Service
public class ConversationService {

    @Resource
    private ConversationRepository conversationRepository;

    @Resource
    private MemberConversationRepository memberConversationRepository;

    @Resource
    private UserRepository userRepository;

    @Transactional
    public Conversation createConversation(Long targetUserId) {
        User currentUser = this.userRepository.getOne(SecurityHelper.getCurrentUserInfo().getId());
        User targetUser = this.userRepository.getOne(targetUserId);

        Conversation conversation = new Conversation();
        conversation.setCreateUser(currentUser);
        conversation.setCreateTime(new Date());
        conversation.setGuid(UUID.randomUUID().toString());
        this.conversationRepository.save(conversation);

        MemberConversation currentMemberConversation = new MemberConversation();
        currentMemberConversation.setConversation(conversation);
        currentMemberConversation.setMemberUser(currentUser);
        currentMemberConversation.setMemberConversationName(targetUser.getNickName());

        MemberConversation targetMemberConversation = new MemberConversation();
        targetMemberConversation.setConversation(conversation);
        targetMemberConversation.setMemberUser(targetUser);
        targetMemberConversation.setMemberConversationName(currentUser.getNickName());
        this.memberConversationRepository.save(currentMemberConversation);
        this.memberConversationRepository.save(targetMemberConversation);
        return conversation;
    }

}
